package com.gla.market.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.gla.market.R;
import com.gla.market.entity.Commodity;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import java.util.List;

public class FYH_CommodityAdapter extends BaseAdapter {

    private Context context;
    private List<Commodity> listCommodity;

    public FYH_CommodityAdapter(Context context, List<Commodity> listCommodity) {
        this.context = context;
        this.listCommodity = listCommodity;

        //实例化ImageLoader
        ImageLoaderConfiguration configuration = ImageLoaderConfiguration.createDefault(context);
        ImageLoader.getInstance().init(configuration);
    }

    @Override
    public int getCount() {
        return listCommodity.size();
    }

    @Override
    public Object getItem(int i) {
        return listCommodity.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup viewGroup) {
        FYH_ShopHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.fyh_shop_card, null);

            //布局文件中所有组件的对象封装到ViewHolder对象中
            holder = new FYH_ShopHolder();
            holder.shopname = convertView.findViewById(R.id.shop_name);
            holder.shophowfar = convertView.findViewById(R.id.shop_howfar);
            holder.shopphoto = convertView.findViewById(R.id.shop_photo);
            holder.shopid = convertView.findViewById(R.id.shop_id);
            //把ViewHolder对象封装到View对象中
            convertView.setTag(holder);
        } else { holder = (FYH_ShopHolder) convertView.getTag(); }

        //获取点击的子菜单的View
        Commodity commodity = listCommodity.get(position);
        String name = commodity.getName();
        if(name.length() > 5) name =  name.substring(0,5) + "...";
        String price = "￥" + commodity.getPriceShow();
        String photo = commodity.getPhoto();
        int spid = commodity.getId();

        holder.shopname.setText(name);
        holder.shophowfar.setText(price);
        holder.shopid.setText(spid + "");
        //绑定图片到控件
        if(!"".equals(photo)) {
            ImageLoader.getInstance().displayImage(photo, holder.shopphoto);
        }else{
            holder.shopphoto.setImageResource(R.drawable.fyh_goods_mr);
        }
        return convertView;
    }
}
